import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation, useParams } from 'react-router-dom';
import api from '../utils/api';
import { RequestError } from '../utils/request';
import { uploadCoverImage, uploadPosterImage, uploadVideo, deleteVideo } from '../utils/oss';
import { userStorage } from '../utils/storage';
import UploadDialog from '../components/UploadDialog';
import './EditCourse.css';

function EditCourse() {
  const navigate = useNavigate();
  const location = useLocation();
  const { courseId } = useParams(); // 从URL参数获取courseId
  
  // 课程数据
  const [courseData, setCourseData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  // 表单数据
  const [courseName, setCourseName] = useState('');
  const [courseDesc, setCourseDesc] = useState('');
  const [courseMembers, setCourseMembers] = useState(['']);
  const [coverImage, setCoverImage] = useState(null);
  const [coverPreview, setCoverPreview] = useState('');
  const [posterImage, setPosterImage] = useState(null);
  const [posterPreview, setPosterPreview] = useState('');
  // 视频列表：每个视频对象包含 { videoUrl(courseVideos中的URL), ossPath(ossVideos中的路径), title, newFile(可选) }
  const [videoList, setVideoList] = useState([]);
  const [currentVideoIndex, setCurrentVideoIndex] = useState(0); // 当前播放的视频索引
  const [previewVideo, setPreviewVideo] = useState(null); // 当前预览的视频
  const [draggedIndex, setDraggedIndex] = useState(null); // 正在拖拽的视频索引
  
  // 提交状态
  const [submitting, setSubmitting] = useState(false);
  
  // 上传进度状态
  const [uploadDialogVisible, setUploadDialogVisible] = useState(false);
  const [currentTask, setCurrentTask] = useState('');
  const [taskProgress, setTaskProgress] = useState(0);
  const [totalTasks, setTotalTasks] = useState(0);
  const [completedTasks, setCompletedTasks] = useState(0);

  // 获取课程详情
  useEffect(() => {
    if (!courseId) {
      alert('缺少课程ID参数');
      navigate('/main/course');
      return;
    }
    
    fetchCourseDetail(courseId);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [courseId]);

  const fetchCourseDetail = async (courseId) => {
    try {
      setLoading(true);
      setError(null);

      console.log('查询课程详情，courseId:', courseId);
      const result = await api.course.getCourseById(courseId);
      
      console.log('课程详情结果:', result);

      if (result) {
        setCourseData(result);
        setCourseName(result.courseName || '');
        setCourseDesc(result.courseDesc || '');
        setCourseMembers(result.courseMembers && result.courseMembers.length > 0 
          ? result.courseMembers 
          : ['']
        );
        setCoverPreview(result.courseThumb || '');
        setPosterPreview(result.coursePoster || '');
        
        // 初始化视频列表
        // courseVideos: 用于播放的URL
        // ossVideos: 用于删除的OSS路径
        const courseVideos = result.courseVideos || [];
        const ossVideos = result.ossVideos || [];
        const titles = result.courseTitles || [];
        
        const videoListData = courseVideos.map((videoUrl, index) => ({
          videoUrl, // courseVideos中的URL，用于播放
          ossPath: ossVideos[index] || '', // ossVideos中的路径，用于删除
          title: titles[index] || '',
        }));
        
        setVideoList(videoListData);
        console.log('加载的视频列表:', videoListData);
      }
    } catch (error) {
      console.error('获取课程详情失败:', error);
      if (error instanceof RequestError) {
        setError(error.message);
      } else {
        setError('获取课程详情失败，请重试');
      }
    } finally {
      setLoading(false);
    }
  };

  // 添加学员电话输入框
  const handleAddPhone = () => {
    setCourseMembers([...courseMembers, '']);
  };

  // 删除学员电话输入框
  const handleRemovePhone = (index) => {
    const newPhones = courseMembers.filter((_, i) => i !== index);
    setCourseMembers(newPhones.length > 0 ? newPhones : ['']);
  };

  // 处理学员电话输入
  const handlePhoneChange = (index, value) => {
    const newPhones = [...courseMembers];
    newPhones[index] = value;
    setCourseMembers(newPhones);
  };

  // 处理封面图片选择
  const handleCoverChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件');
        return;
      }
      
      setCoverImage(file);
      
      const reader = new FileReader();
      reader.onloadend = () => {
        setCoverPreview(reader.result);
      };
      reader.readAsDataURL(file);
    }
  };

  // 处理海报图片选择
  const handlePosterChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件');
        return;
      }
      
      setPosterImage(file);
      
      const reader = new FileReader();
      reader.onloadend = () => {
        setPosterPreview(reader.result);
      };
      reader.readAsDataURL(file);
    }
  };

  // 添加新视频
  const handleAddVideo = (e) => {
    const files = Array.from(e.target.files);
    
    const validVideos = [];
    for (let file of files) {
      if (!file.type.startsWith('video/')) {
        alert(`${file.name} 不是视频文件，已跳过`);
        continue;
      }
      
      const previewUrl = URL.createObjectURL(file);
      validVideos.push({
        videoUrl: '', // 新视频还没有URL
        ossPath: '', // 新视频还没有OSS路径
        title: '',
        newFile: file,
        previewUrl: previewUrl,
      });
    }
    
    setVideoList([...videoList, ...validVideos]);
    
    // 重置文件输入
    e.target.value = '';
  };

  // 删除视频
  const handleRemoveVideo = (index) => {
    if (!window.confirm('确定要删除这个视频吗？')) {
      return;
    }
    
    const videoToRemove = videoList[index];
    
    // 释放预览 URL
    if (videoToRemove.previewUrl) {
      URL.revokeObjectURL(videoToRemove.previewUrl);
    }
    
    // 如果删除的是正在预览的视频，关闭预览
    if (previewVideo && (previewVideo.videoUrl === videoToRemove.videoUrl || previewVideo === videoToRemove)) {
      setPreviewVideo(null);
    }
    
    // 从数组中移除视频
    const newVideoList = videoList.filter((_, i) => i !== index);
    setVideoList(newVideoList);
    
    // 更新当前播放索引
    if (currentVideoIndex >= newVideoList.length && newVideoList.length > 0) {
      setCurrentVideoIndex(newVideoList.length - 1);
    } else if (newVideoList.length === 0) {
      setCurrentVideoIndex(0);
    }
  };

  // 预览视频
  const handlePreviewVideo = (videoItem) => {
    setPreviewVideo(videoItem);
  };

  // 关闭预览
  const handleClosePreview = () => {
    setPreviewVideo(null);
  };

  // 拖拽开始
  const handleDragStart = (e, index) => {
    setDraggedIndex(index);
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', e.currentTarget);
  };

  // 处理视频标题修改
  const handleVideoTitleChange = (index, title) => {
    const newVideoList = [...videoList];
    newVideoList[index] = {
      ...newVideoList[index],
      title: title
    };
    setVideoList(newVideoList);
  };

  // 处理单个视频重新上传
  const handleReuploadVideo = (index, e) => {
    const file = e.target.files[0];
    if (!file) return;
    
    if (!file.type.startsWith('video/')) {
      alert('请选择视频文件');
      return;
    }
    
    const newVideoList = [...videoList];
    const previewUrl = URL.createObjectURL(file);
    newVideoList[index] = {
      ...newVideoList[index],
      newFile: file,
      previewUrl: previewUrl
    };
    setVideoList(newVideoList);
    
    // 重置文件输入
    e.target.value = '';
  };

  // 拖拽经过
  const handleDragOver = (e, index) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';

    if (draggedIndex === null || draggedIndex === index) {
      return;
    }

    // 交换位置
    const newVideoList = [...videoList];
    const draggedVideo = newVideoList[draggedIndex];
    
    // 移除拖拽的元素
    newVideoList.splice(draggedIndex, 1);
    // 插入到新位置
    newVideoList.splice(index, 0, draggedVideo);
    
    setVideoList(newVideoList);
    setDraggedIndex(index);
  };

  // 拖拽结束
  const handleDragEnd = () => {
    setDraggedIndex(null);
  };

  // 组件卸载时清理所有预览 URL
  useEffect(() => {
    return () => {
      videoList.forEach(video => {
        if (video.previewUrl) {
          URL.revokeObjectURL(video.previewUrl);
        }
      });
    };
  }, [videoList]);

  // 提交更新
  const handleSubmit = async () => {
    // 验证
    if (!courseName.trim()) {
      alert('请输入课程名称');
      return;
    }
    if (!courseDesc.trim()) {
      alert('请输入课程描述');
      return;
    }
    
    // 验证至少有一个视频
    if (videoList.length === 0) {
      alert('至少需要保留一个视频');
      return;
    }

    setSubmitting(true);
    setUploadDialogVisible(true);

    try {
      const userInfo = userStorage.getUserInfo();
      if (!userInfo) {
        alert('未获取到用户信息，请重新登录');
        navigate('/login');
        return;
      }
      const phone = userInfo.phone;

      let coverPath = courseData.courseThumb || '';
      let posterPath = courseData.coursePoster || '';
      
      // 获取原始OSS路径列表（用于对比，找出被删除的视频）
      const originalOssPaths = new Set(courseData.ossVideos || []);
      
      // 计算总任务数：是否有新封面 + 是否有新海报 + 需要重新上传的视频数量
      let totalTaskCount = 0;
      if (coverImage) totalTaskCount += 1;
      if (posterImage) totalTaskCount += 1;
      const reuploadCount = videoList.filter(v => v.newFile).length;
      totalTaskCount += reuploadCount;
      
      setTotalTasks(totalTaskCount);
      setCompletedTasks(0);

      let completedCount = 0;

      // 如果有新封面，上传封面
      if (coverImage) {
        setCurrentTask('封面图片上传中');
        setTaskProgress(0);
        
        coverPath = await uploadCoverImage(
          coverImage,
          phone,
          courseData._id,
          (progress) => {
            setTaskProgress(progress * 100);
          }
        );
        
        completedCount += 1;
        setCompletedTasks(completedCount);
        console.log('封面图片上传成功:', coverPath);
      }

      // 如果有新海报，上传海报
      if (posterImage) {
        setCurrentTask('海报图片上传中');
        setTaskProgress(0);
        
        posterPath = await uploadPosterImage(
          posterImage,
          phone,
          courseData._id,
          (progress) => {
            setTaskProgress(progress * 100);
          }
        );
        
        completedCount += 1;
        setCompletedTasks(completedCount);
        console.log('海报图片上传成功:', posterPath);
      }

      // 处理视频：构建新的courseVideos和ossVideos数组
      const courseVideos = []; // 用于播放的URL
      const courseTitles = [];
      const oldOssPathsToDelete = [];
      const newOssPathsMap = new Map(); // 存储新上传视频的OSS路径映射（index -> ossPath）
      
      // 第一遍：处理新上传的视频，并构建courseVideos数组
      for (let i = 0; i < videoList.length; i++) {
        const videoItem = videoList[i];
        
        if (videoItem.newFile) {
          // 需要重新上传的视频
          setCurrentTask(`视频 ${i + 1} 上传中`);
          setTaskProgress(0);
          
          // 如果原有OSS路径存在，标记为待删除
          if (videoItem.ossPath && videoItem.ossPath.trim() !== '') {
            oldOssPathsToDelete.push(videoItem.ossPath);
            console.log('标记待删除的旧视频文件（被替换）:', videoItem.ossPath);
          }
          
          // 上传新视频
          const ossPath = await uploadVideo(
            videoItem.newFile,
            phone,
            courseData._id,
            i,
            (progress) => {
              setTaskProgress(progress * 100);
            }
          );
          
          // 新上传的视频，OSS路径就是播放URL
          courseVideos.push(ossPath);
          newOssPathsMap.set(i, ossPath); // 记录新上传视频的OSS路径
          
          completedCount += 1;
          setCompletedTasks(completedCount);
          console.log(`视频 ${i + 1} 上传成功:`, ossPath);
        } else if (videoItem.ossPath && videoItem.ossPath.trim() !== '') {
          // 使用原有视频（没有删除，使用ossVideos中的路径作为courseVideos的值）
          courseVideos.push(videoItem.ossPath);
          console.log(`视频 ${i + 1} 使用ossVideos中的路径:`, videoItem.ossPath);
        } else if (videoItem.videoUrl && videoItem.videoUrl.trim() !== '') {
          // 如果没有ossPath，使用videoUrl（向后兼容）
          courseVideos.push(videoItem.videoUrl);
          console.log(`视频 ${i + 1} 使用videoUrl（向后兼容）:`, videoItem.videoUrl);
        } else {
          console.warn(`视频 ${i + 1} 没有有效的路径，跳过`);
          continue;
        }
        
        courseTitles.push(videoItem.title || '');
      }
      
      // 检查是否有视频被删除或更改
      const originalVideoCount = (courseData.courseVideos || []).length;
      const newVideoCount = courseVideos.length;
      const hasVideoDeleted = originalVideoCount !== newVideoCount;
      const hasVideoReuploaded = newOssPathsMap.size > 0;
      const hasVideoChanged = hasVideoDeleted || hasVideoReuploaded;
      
      // 找出被删除的视频（在原始ossVideos中但不在新列表中的）
      const currentOssPaths = new Set();
      videoList.forEach(item => {
        if (item.ossPath && item.ossPath.trim() !== '') {
          currentOssPaths.add(item.ossPath);
        }
      });
      
      originalOssPaths.forEach(ossPath => {
        if (!currentOssPaths.has(ossPath)) {
          oldOssPathsToDelete.push(ossPath);
          console.log('标记待删除的视频文件（被删除）:', ossPath);
        }
      });
      
      // 去重（避免重复删除）
      const uniquePathsToDelete = [...new Set(oldOssPathsToDelete)];
      console.log('最终需要删除的OSS文件:', uniquePathsToDelete);
      console.log('是否有视频变化:', hasVideoChanged);

      // 调用更新接口
      setCurrentTask('更新课程信息中');
      setTaskProgress(100);
      
      // 过滤掉空的电话号码
      const validPhones = courseMembers.filter(phone => phone.trim() !== '');
      
      // 构建更新数据对象
      const courseUpdateData = {
        teacherPhone: courseData.teacherPhone,
        courseName: courseName.trim(),
        courseDesc: courseDesc.trim(),
        courseMembers: validPhones,
      };

      // 只有重新上传了封面才包含 courseThumb 字段
      if (coverImage) {
        courseUpdateData.courseThumb = coverPath;
      }

      // 只有重新上传了海报才包含 coursePoster 字段
      if (posterImage) {
        courseUpdateData.coursePoster = posterPath;
      }

      // 更新视频列表和标题
      // 注意：ossVideos字段不入库，只是接口返回时带回的，所以提交时不包含此字段
      courseUpdateData.courseVideos = courseVideos; // 用于播放的URL
      courseUpdateData.courseTitles = courseTitles;

      console.log('准备更新课程，参数:', courseUpdateData);
      console.log('courseVideos（播放URL）:', courseVideos);
      console.log('注意：ossVideos字段不入库，仅用于删除OSS文件');
      
      // 先更新数据库，成功后再删除OSS文件
      await api.course.updateCourse(courseData._id, courseUpdateData);
      
      console.log('课程更新成功');

      // 数据库更新成功后，删除不再使用的旧视频文件
      if (uniquePathsToDelete.length > 0) {
        console.log(`准备删除 ${uniquePathsToDelete.length} 个不再使用的旧视频文件:`, uniquePathsToDelete);
        
        // 异步删除，不等待结果（避免影响用户体验）
        Promise.all(
          uniquePathsToDelete.map(path => {
            console.log(`开始删除OSS文件: ${path}`);
            return deleteVideo(path)
              .then(() => {
                console.log(`✓ 成功删除OSS文件: ${path}`);
              })
              .catch(err => {
                console.warn(`✗ 删除OSS文件失败: ${path}`, err);
              });
          })
        ).then(() => {
          console.log(`✓ 所有旧视频文件清理完成，共删除 ${uniquePathsToDelete.length} 个文件`);
        }).catch(err => {
          console.error('清理旧视频文件时出错:', err);
        });
      } else {
        console.log('没有需要删除的旧视频文件');
      }

      setUploadDialogVisible(false);
      alert('课程更新成功！');
      navigate('/main/course', { replace: true });

    } catch (error) {
      setSubmitting(false);
      setUploadDialogVisible(false);
      
      if (error instanceof RequestError) {
        console.error('更新失败:', error.message);
        alert(`更新失败: ${error.message}`);
      } else {
        console.error('更新失败:', error);
        alert(`更新失败: ${error.message || '未知错误'}`);
      }
    }
  };

  // 组件卸载时清理预览 URL
  useEffect(() => {
    return () => {
      videoList.forEach(video => {
        if (video.previewUrl) {
          URL.revokeObjectURL(video.previewUrl);
        }
      });
    };
  }, [videoList]);

  if (loading) {
    return (
      <div className="edit-course-container">
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <p>加载中...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="edit-course-container">
        <div className="error-container">
          <p className="error-message">❌ {error}</p>
          <button className="retry-btn" onClick={() => fetchCourseDetail(courseId)}>
            重试
          </button>
          <button className="back-btn" onClick={() => navigate('/main/course')}>
            返回列表
          </button>
        </div>
      </div>
    );
  }

  if (!courseData) {
    return null;
  }

  return (
    <div className="edit-course-container">
      <div className="edit-course-box">
        <h2>编辑课程</h2>
        
        <form onSubmit={(e) => e.preventDefault()}>
          {/* 教师信息（不可编辑） */}
          <div className="form-group readonly-group">
            <label>教师手机号（不可编辑）</label>
            <input
              type="text"
              value={courseData.teacherPhone}
              readOnly
              disabled
            />
          </div>

          {/* 课程名称 */}
          <div className="form-group">
            <label className="required">课程名称</label>
            <input
              type="text"
              value={courseName}
              onChange={(e) => setCourseName(e.target.value)}
              placeholder="请输入课程名称"
            />
          </div>

          {/* 课程描述 */}
          <div className="form-group">
            <label className="required">课程描述</label>
            <textarea
              value={courseDesc}
              onChange={(e) => setCourseDesc(e.target.value)}
              placeholder="请输入课程描述"
              rows="4"
            ></textarea>
          </div>

          {/* 参课学生 */}
          <div className="form-group">
            <label>参课学生电话</label>
            {courseMembers.map((phone, index) => (
              <div key={index} className="phone-input-group">
                <input
                  type="tel"
                  value={phone}
                  onChange={(e) => handlePhoneChange(index, e.target.value)}
                  placeholder="请输入学生电话"
                  maxLength="11"
                />
                {courseMembers.length > 1 && (
                  <button
                    type="button"
                    className="remove-phone-btn"
                    onClick={() => handleRemovePhone(index)}
                  >
                    删除
                  </button>
                )}
              </div>
            ))}
            <button
              type="button"
              className="add-phone-btn"
              onClick={handleAddPhone}
            >
              添加学生电话
            </button>
          </div>

          {/* 封面图片 */}
          <div className="form-group">
            <label>课程封面</label>
            {coverPreview && (
              <div className="cover-preview">
                <img src={coverPreview} alt="课程封面" />
              </div>
            )}
            <input
              type="file"
              id="cover-upload"
              accept="image/*"
              onChange={handleCoverChange}
              style={{ display: 'none' }}
            />
            <label htmlFor="cover-upload" className="upload-btn">
              {coverPreview ? '重新上传封面' : '上传封面'}
            </label>
            <p className="upload-tip">支持 JPG、PNG 格式，大小不超过 5MB</p>
          </div>

          {/* 海报图片 */}
          <div className="form-group">
            <label>课程海报</label>
            {posterPreview && (
              <div className="cover-preview">
                <img src={posterPreview} alt="课程海报" />
              </div>
            )}
            <input
              type="file"
              id="poster-upload"
              accept="image/*"
              onChange={handlePosterChange}
              style={{ display: 'none' }}
            />
            <label htmlFor="poster-upload" className="upload-btn">
              {posterPreview ? '重新上传海报' : '上传海报'}
            </label>
            <p className="upload-tip">支持 JPG、PNG 格式，大小不超过 5MB</p>
          </div>

          {/* 课程视频 */}
          <div className="form-group">
            <label>课程视频</label>
            
            {videoList.length > 0 && (
              <div className="video-list">
                <div className="list-header">
                  共 {videoList.length} 个视频
                  <span className="drag-tip">（可拖动排序）</span>
                </div>
                {videoList.map((videoItem, arrayIndex) => {
                  // 优先使用预览URL（新上传的文件），其次使用videoUrl（已有文件）
                  const videoUrl = videoItem.newFile 
                    ? videoItem.previewUrl 
                    : videoItem.videoUrl;
                  
                  return (
                    <div
                      key={arrayIndex}
                      className={`video-item ${draggedIndex === arrayIndex ? 'dragging' : ''}`}
                      draggable="true"
                      onDragStart={(e) => handleDragStart(e, arrayIndex)}
                      onDragOver={(e) => handleDragOver(e, arrayIndex)}
                      onDragEnd={handleDragEnd}
                    >
                      <span className="drag-handle" title="拖动排序">
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                          <circle cx="4" cy="4" r="1.5"/>
                          <circle cx="4" cy="8" r="1.5"/>
                          <circle cx="4" cy="12" r="1.5"/>
                          <circle cx="12" cy="4" r="1.5"/>
                          <circle cx="12" cy="8" r="1.5"/>
                          <circle cx="12" cy="12" r="1.5"/>
                        </svg>
                      </span>
                      <span className="video-index">{arrayIndex + 1}</span>
                      <div className="video-info-group">
                        <div className="video-preview-thumbnail">
                          <video
                            src={videoUrl}
                            preload="metadata"
                            onLoadedMetadata={(e) => {
                              e.target.currentTime = 1;
                            }}
                          />
                        </div>
                        <div className="video-title-wrapper">
                          <input
                            type="text"
                            className="video-title-input"
                            placeholder="请输入视频标题"
                            value={videoItem.title || ''}
                            onChange={(e) => handleVideoTitleChange(arrayIndex, e.target.value)}
                            maxLength="50"
                          />
                        </div>
                      </div>
                      <div className="video-actions">
                        <button
                          type="button"
                          className="preview-video-btn"
                          onClick={() => handlePreviewVideo(videoItem)}
                        >
                          预览
                        </button>
                        <label className="reupload-video-btn">
                          重新上传
                          <input
                            type="file"
                            accept="video/*"
                            onChange={(e) => handleReuploadVideo(arrayIndex, e)}
                            style={{ display: 'none' }}
                          />
                        </label>
                        <button
                          type="button"
                          className="remove-video-btn"
                          onClick={() => handleRemoveVideo(arrayIndex)}
                        >
                          删除
                        </button>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
            
            {videoList.length === 0 && (
              <p className="upload-tip" style={{ color: '#999', fontStyle: 'italic' }}>
                暂无视频，请先添加视频
              </p>
            )}
            
            {/* 添加新视频按钮 */}
            <div style={{ marginTop: '16px' }}>
              <input
                type="file"
                id="add-video-upload"
                accept="video/*"
                multiple
                onChange={handleAddVideo}
                style={{ display: 'none' }}
              />
              <label htmlFor="add-video-upload" className="upload-btn" style={{ display: 'inline-block' }}>
                + 添加新视频
              </label>
              <p className="upload-tip">支持 MP4、AVI、MOV 等格式</p>
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="form-actions">
            <button
              type="button"
              className="cancel-btn"
              onClick={() => navigate('/main/course')}
              disabled={submitting}
            >
              取消
            </button>
            <button
              type="button"
              className="submit-btn"
              onClick={handleSubmit}
              disabled={submitting}
            >
              {submitting ? '提交中...' : '保存更改'}
            </button>
          </div>
        </form>
      </div>

      {/* 上传进度对话框 */}
      <UploadDialog
        visible={uploadDialogVisible}
        currentTask={currentTask}
        progress={taskProgress}
        totalTasks={totalTasks}
        completedTasks={completedTasks}
      />

      {/* 视频预览模态框 */}
      {previewVideo && (
        <div className="video-preview-modal" onClick={handleClosePreview}>
          <div className="preview-content" onClick={(e) => e.stopPropagation()}>
            <button className="close-preview-btn" onClick={handleClosePreview}>
              ✕
            </button>
            <h3>视频预览</h3>
            <video
              controls
              autoPlay
              src={
                previewVideo.newFile 
                  ? previewVideo.previewUrl 
                  : previewVideo.videoUrl
              }
              className="preview-video"
            >
              您的浏览器不支持视频预览
            </video>
            <p className="preview-filename">
              {previewVideo.newFile 
                ? previewVideo.newFile.name 
                : (() => {
                    const index = videoList.findIndex(v => v.videoUrl === previewVideo.videoUrl);
                    return index >= 0 ? `视频 ${index + 1}` : '视频';
                  })()}
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

export default EditCourse;

